<template>
  <div class="dt-password-login">
    <AForm
        ref="loginForm"
        :model="ruleForm"
        :rules="rules"
        class="login-form"
        @keypress.enter="submitForm"
    >
      <AFormItem name="userName">
        <AInput v-model:value="ruleForm.userName" placeholder="请输入账号" />
      </AFormItem>

      <AFormItem name="userPass">
        <AInput v-model:value="ruleForm.userPass" type="password" placeholder="请输入密码" />
      </AFormItem>

      <div class="login-pwd">
        <ACheckbox v-model:checked="ruleForm.remember">记住密码</ACheckbox>

        <!-- <a>忘记密码?</a> -->
      </div>

      <AButton type="primary" @click="submitForm">登录</AButton>
    </AForm>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'

import { Ahttp, DtCache, CacheKey, useAppStore, setDynamicRoute, getFirstMenu } from '@zm-pkg/core4'
import { LOGIN_CONF } from '../config/config'
import { useResource } from '../hooks/useAuth'

const router = useRouter()

const loginForm = ref()
const ruleForm = reactive(LOGIN_CONF.RULE_FORM)
const rules = LOGIN_CONF.RULES as any

const COOKIE_USER_INFO = 'DT_COOKIE_USER_INFO_'

const { userName, userPass, remember } = {
  userName: null,
  userPass: null,
  remember: null
}

ruleForm.userName = userName
ruleForm.userPass = userPass
ruleForm.remember = remember


// 表单提交
function submitForm() {
  unref(loginForm).validate()
      .then( () => {
        Ahttp
            .post('/api-auth/login', unref(ruleForm))
            .then( data => {
              if( !data ) return

              // 记住密码
              if( unref(ruleForm).remember ) {

              } else {

              }

              // 设置权限路由
              setDynamicRoute()

              const { buttonResource, roles, resources, userInfo, authorizeToken } = data

              DtCache.setLocal( CacheKey.TOKEN, authorizeToken )
              DtCache.setLocal( CacheKey.AUTHS, buttonResource )
              DtCache.setLocal( CacheKey.USER_INFO, userInfo )
              DtCache.setLocal( CacheKey.MENUS, useResource(resources) )

              // 跳转至第一个可用菜单
              router.replace( getFirstMenu())

            } )
      } )
      .catch(err => {
        console.log('请检查输入内容!');
      })
}

</script>

<style lang="less">

.dt-password-login{
  .el-form-item{
    position: relative;
    margin-top: 30px;
    label{
      position: absolute;
      left: 0;
      z-index: 1;
      &::before{
        content: ''
      }
    }
  }

  .el-input{
    input{
      padding-left: 60px;
      border-radius: 0;
      border-top: none;
      border-left: none;
      border-right: none;
    }
  }

  .ant-checkbox-wrapper{
    span{
      color: #999;
    }
  }

  .ant-btn-primary{
    width: 100%;
    margin-top: 30px;
    border-radius: 3px;
    letter-spacing: 10px;
  }

  .login-pwd{
    display: flex;
    justify-content: space-between;
    margin-top: 30px;
  }
}
</style>
